package com.chat.security.provider;

import com.alibaba.fastjson2.JSON;
import com.chat.security.authentication.TokenAuthentication;
import com.chat.security.entity.JWTLoginUser;
import com.chat.security.service.JwtTokenService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class TokenProvider implements AuthenticationProvider {
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        TokenAuthentication tokenAuthentication = (TokenAuthentication) authentication;

        final Map<String, Object> claims = tokenAuthentication.getTokenService().getClaims(authentication.getDetails().toString());
        final JWTLoginUser loginUser = JSON.parseObject(claims.get(JwtTokenService.LOGIN_USER_KEY).toString(),JWTLoginUser.class);
        tokenAuthentication.setLoginUser(loginUser);
        tokenAuthentication.setAuthenticated(true);
        return tokenAuthentication;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.isAssignableFrom(TokenAuthentication.class);
    }
}
